package com.yinda.dt.produce.module.mine;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.xcgame.oh.DownloadResponseCallback;
import com.xcgame.wpp.WxPicturePickerActivity;
import com.yinda.dt.produce.R;
import com.yinda.dt.produce.app.DemoActivity;
import com.yinda.dt.produce.app.DemoConfig;
import com.yinda.dt.produce.app.MyResponseCallback;
import com.yinda.dt.produce.app.MyUploadResponseCallback;
import com.yinda.dt.produce.module.login.LoginActivity;
import com.yinda.dt.produce.utils.ApplicationUtil;
import com.yinda.dt.produce.view.HintDialog;
import com.yinda.dt.produce.view.ProgressDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;

import cn.jpush.android.api.JPushInterface;
import de.hdodenhof.circleimageview.CircleImageView;

public class MineActivity extends DemoActivity implements View.OnClickListener {

    private CircleImageView civ_userHeadImg;
    private TextView tv_username;
    private TextView tv_userID;

    private LinearLayout ll_push;
    private ImageView iv_push;

    private LinearLayout ll_clearCache;
    private LinearLayout ll_about;
    private LinearLayout ll_advise;
    private LinearLayout ll_checkVersion;

    private TextView tv_check;
    private TextView tv_version;

    private Button bt_exit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mine);

        tv_username = (TextView) findViewById(R.id.tv_username);
        tv_username.setText(DemoConfig.getInstance(this).getName());
        tv_userID = (TextView) findViewById(R.id.tv_userID);
        tv_userID.setText(DemoConfig.getInstance(this).getAccout());

        civ_userHeadImg = (CircleImageView) findViewById(R.id.civ_userHeadImg);
        civ_userHeadImg.setOnClickListener(this);
        Glide.with(this).load(DemoConfig.getInstance(this).getUserimgUrl()).asBitmap().placeholder(R.drawable.default_head).error(R.drawable.default_head).into(civ_userHeadImg);

        ll_push = (LinearLayout) findViewById(R.id.ll_push);
        iv_push = (ImageView) findViewById(R.id.iv_push);
        if (DemoConfig.getInstance(this).isPush()) {
            iv_push.setImageResource(R.drawable.mine_push_open);
        } else {
            iv_push.setImageResource(R.drawable.mine_push_close);
        }
        ll_push.setOnClickListener(this);
        ll_clearCache = (LinearLayout) findViewById(R.id.ll_clearCache);
        ll_clearCache.setOnClickListener(this);

        ll_about = (LinearLayout) findViewById(R.id.ll_about);
        ll_about.setOnClickListener(this);

        ll_advise = (LinearLayout) findViewById(R.id.ll_advise);
        ll_advise.setOnClickListener(this);

        ll_checkVersion = (LinearLayout) findViewById(R.id.ll_checkVersion);
        ll_checkVersion.setOnClickListener(this);

        tv_check = (TextView) findViewById(R.id.tv_check);
        tv_version = (TextView) findViewById(R.id.tv_version);
        if (DemoConfig.getInstance(this).getNewVersionCode() > ApplicationUtil.getThisAPPVersionCode(this)) {
            tv_check.setVisibility(View.VISIBLE);
            tv_version.setVisibility(View.VISIBLE);
            tv_version.setText("v" + DemoConfig.getInstance(this).getNewVersionName());
        } else {
            tv_check.setVisibility(View.GONE);
            tv_version.setVisibility(View.GONE);
        }

        bt_exit = (Button) findViewById(R.id.bt_exit);
        bt_exit.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.ll_push) {
            if (DemoConfig.getInstance(this).isPush()) {
                DemoConfig.getInstance(this).setIsPush(false);
                iv_push.setImageResource(R.drawable.mine_push_close);
                showToast("推送开关以关闭！");
                JPushInterface.stopPush(this);
            } else {
                DemoConfig.getInstance(this).setIsPush(true);
                iv_push.setImageResource(R.drawable.mine_push_open);
                showToast("推送开关以打开！");
                JPushInterface.resumePush(this);
            }
        }
        if (id == R.id.ll_clearCache) {

            HintDialog hintDialog = new HintDialog(this);
            hintDialog.setTitle("温馨提示");
            hintDialog.setContent("是否清除缓存信息？");
            hintDialog.setCanceledOnTouchOutside(false);
            hintDialog.setCancelable(false);
            hintDialog.setConfirmButtonText("确定");
            hintDialog.setCancelButtonText("取消");
            hintDialog.setOnClickListener(new HintDialog.OnClickListener() {
                @Override
                public void onConfirm(Dialog dialog) {
                    dialog.dismiss();
                    Thread thread = new Thread() {
                        @Override
                        public void run() {
                            // 必须在后台线程中调用，建议同时clearMemory()
                            Glide.get(getApplicationContext()).clearDiskCache();
                        }
                    };
                    thread.start();
                    // 必须在UI线程中调用
                    Glide.get(MineActivity.this).clearMemory();
                    showToast("清除成功！");
                }

                @Override
                public void onCancel(Dialog dialog) {
                    dialog.dismiss();
                }
            });
            hintDialog.show();
        }
        if (id == R.id.ll_about) {
            Intent intent = new Intent(this, AboutUsActivity.class);
            startActivity(intent);
        }
        if (id == R.id.ll_advise) {
            Intent intent = new Intent(this, AdviseActivity.class);
            startActivity(intent);
        }
        if (id == R.id.ll_checkVersion) {
            checkVersion();
        }
        if (id == R.id.bt_exit) {

            DemoConfig.getInstance(this).setIsLogin(false);

            Intent intent = new Intent(this, LoginActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
        }
        if (id == R.id.civ_userHeadImg) {
            WxPicturePickerActivity.startIconSelector(this, 125);
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 125 && resultCode == RESULT_OK) {
            ArrayList<String> pictures = (ArrayList<String>) data.getSerializableExtra(WxPicturePickerActivity.RESULT_KEY);
            upload(pictures.get(0));
        }
    }


    private void upload(String picturePath) {

        loadingDialog.setLoadingText("上传中...");

        try {
            String url = getString(R.string.defaultURL) + "/phone1_0!upload.action";
            JSONObject jsonParams = new JSONObject();
            jsonParams.put("imgDataFileName", "DT_" + System.currentTimeMillis());

            uploadFile(url, null, new File(picturePath), new MyUploadResponseCallback(loadingDialog) {
                @Override
                public void onSuccess(JSONObject jsonResult) {
                    super.onSuccess(jsonResult);

                    try {
                        JSONObject jsonHead = jsonResult.getJSONObject("head");
                        int status = jsonHead.getInt("status");
                        String info = jsonHead.getString("info");
                        if (status == 1) {
                            JSONObject jsonData = jsonResult.getJSONObject("data");
                            setUserInfo(jsonData.getString("url"));
                        } else {
                            if (info.contains("key无效") || info.toLowerCase().contains("loginout") || info.contains("未登录")) {
                                DemoConfig.getInstance(getContext()).setKey("");
                                DemoConfig.getInstance(getContext()).setIsLogin(false);
                                showToast("请重新登录");
                                Intent intent = new Intent(getContext(), LoginActivity.class);
                                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                                startActivity(intent);
                            } else {
                                showToast(info);
                            }
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void setUserInfo(final String userimgUrl) {

        loadingDialog.setLoadingText("上传中...");

        try {
            String url = getString(R.string.defaultURL) + "/phone1_0!setUserInfo.action";
            JSONObject jsonParams = new JSONObject();
            jsonParams.put("tel", DemoConfig.getInstance(this).getTel());
            jsonParams.put("name", DemoConfig.getInstance(this).getName());
            jsonParams.put("portrait", userimgUrl);
            jsonParams.put("encrypt", true);
            post(url, jsonParams, new MyResponseCallback(loadingDialog) {
                @Override
                public void onSuccess(JSONObject jsonResult) {
                    super.onSuccess(jsonResult);

                    try {
                        JSONObject jsonHead = jsonResult.getJSONObject("head");
                        int status = jsonHead.getInt("status");
                        String info = jsonHead.getString("info");
                        if (status == 1) {
                            DemoConfig.getInstance(getContext()).setUserimgUrl(userimgUrl);
                            DemoConfig.getInstance(getContext()).setUserimgUpdate(true);
                            Glide.with(getContext()).load(userimgUrl).asBitmap().placeholder(R.drawable.default_head).error(R.drawable.default_head).into(civ_userHeadImg);
                            showToast("头像修改完成！");
                        } else {
                            if (info.contains("key无效") || info.toLowerCase().contains("loginout") || info.contains("未登录")) {
                                DemoConfig.getInstance(getContext()).setKey("");
                                DemoConfig.getInstance(getContext()).setIsLogin(false);
                                showToast("请重新登录");
                                Intent intent = new Intent(getContext(), LoginActivity.class);
                                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                                startActivity(intent);
                            } else {
                                showToast(info);
                            }
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 检查版本
     */
    public void checkVersion() {

        loadingDialog.setLoadingText("请求中...");

        String url = getString(R.string.defaultURL) + "/phone1_0!checkUpdate.action";
        JSONObject jsonParams = new JSONObject();
        post(url, jsonParams, new MyResponseCallback(loadingDialog) {

            @Override
            public void onSuccess(JSONObject jsonResult) {
                super.onSuccess(jsonResult);

                try {

                    JSONObject jsonHead = jsonResult.getJSONObject("head");
                    int status = jsonHead.getInt("status");
                    String info = jsonHead.getString("info");
                    if (status == 1) {
                        JSONObject jsonData = jsonResult.getJSONObject("data");
                        String updateContent = jsonData.getString("updateContent");
                        int updateVersionCode = jsonData.getInt("updateVersionCode");
                        String updateVersionName = jsonData.getString("updateVersionName");
                        String updateUrl = jsonData.getString("updateUrl");
                        boolean forced;
                        if (jsonData.getString("forced").equals("0")) {
                            forced = false;
                        } else {
                            forced = true;
                        }

                        if (updateVersionCode > ApplicationUtil.getThisAPPVersionCode(getContext())) {
                            tv_check.setVisibility(View.VISIBLE);
                            tv_version.setVisibility(View.VISIBLE);
                            tv_version.setText("v" + updateVersionCode);
                        } else {
                            tv_check.setVisibility(View.GONE);
                            tv_version.setVisibility(View.GONE);
                        }

                        DemoConfig.getInstance(getContext()).setNewVersionCode(updateVersionCode);
                        DemoConfig.getInstance(getContext()).setNewVersionName(updateVersionName);
                        DemoConfig.getInstance(getContext()).setUpdateAppUrl(updateUrl);

                        checkAppUpdate(updateContent, updateVersionCode, updateVersionName, updateUrl, forced);

                    } else {
                        showToast(info);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });

    }

    private void checkAppUpdate(String updateContent, int updateVersionCode, String updateVersionName, final String updateUrl, boolean isForced) {
        if (ApplicationUtil.isNeedUpdate(this, updateVersionCode)) {
            HintDialog hintDialog = new HintDialog(this);
            hintDialog.setTitle("温馨提示");
            hintDialog.setContent(updateContent);
            hintDialog.setCanceledOnTouchOutside(false);
            hintDialog.setCancelable(false);
            hintDialog.setConfirmButtonText("立即更新");
            hintDialog.setCancelButtonText("稍后更新");
            hintDialog.setOnClickListener(new HintDialog.OnClickListener() {
                @Override
                public void onConfirm(Dialog dialog) {
                    dialog.dismiss();
                    network_downloadApp(updateUrl, false);
                }

                @Override
                public void onCancel(Dialog dialog) {
                    dialog.dismiss();
                }
            });
            hintDialog.show();
        } else {
            showToast("当前已是最新版本！");
        }
    }

    private void network_downloadApp(String url, final boolean isForced) {

        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setCancelable(false);
        progressDialog.setProgress(0);
        myOkHttp.downloadFile(this, url, new DownloadResponseCallback() {

            @Override
            public void onStart() {
                super.onStart();
                progressDialog.show();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                progressDialog.dismiss();
            }

            @Override
            public void onProgress(int progress) {
                super.onProgress(progress);
                progressDialog.setProgress(progress);
            }

            @Override
            public void onSuccess(String filePath) {
                super.onSuccess(filePath);

                ApplicationUtil.installApk(MineActivity.this, filePath);
            }

        });
    }

}
